<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>网页涂鸦</title>
</head>

<body>
    <canvas id="cansElem">

    </canvas>
    <script>
        var canvas = document.getElementById('cansElem'); // 获得画布
        // 准备画笔（获取上下文对象）
        var context = canvas.getContext('2d');
        context.lineWidth = '3';
        context.strokeStyle = '#000'
            // 设置标签的宽高和边框
        canvas.width = 900;
        canvas.height = 600;
        canvas.style.border = '1px solid #f00';


        // 当鼠标按下触发onmousedown事件时，定义一个函数获取鼠标起始坐标
        canvas.onmousedown = function(e) {
            console.log(canvas.getBoundingClientRect());
            console.log(e.clientX, e.clientY)
            var x = e.clientX - canvas.getBoundingClientRect().left;
            var y = e.clientY - canvas.getBoundingClientRect().top;
            context.beginPath();
            context.moveTo(x, y);
            // 当鼠标移动触发onmousemove事件时，定义一个函数获取绘制线条的坐标
            canvas.onmousemove = function(event) {
                console.log('绘图中...');
                var x = event.clientX - canvas.getBoundingClientRect().left;
                var y = event.clientY - canvas.getBoundingClientRect().top;
                context.lineTo(x, y);
                context.stroke();
            };
            // 当鼠标按键被松开时，onmousemove函数返回null
            canvas.onmouseup = function(event) {
                console.log('取消绘制');
                canvas.onmousemove = null;
            };
        };
    </script>
</body>

</html>